package com.wgz.sbm.controller;

import com.wgz.sbm.bean.User;
import com.wgz.sbm.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 王宫泽
 * @date 2021/4/11
 */
@Controller
public class UserController {
    @Autowired
    UserMapper userMapper;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @PostMapping("/login")
    public String login(User user, HttpSession session, Model model)  {
        //用户名密码校验
        if ("wanggongze".equals(user.getUsername()) && "18044224".equals(user.getPassword())) {
            //登陆成功
            session.setAttribute("user", user);
            //跳转页面
            return "redirect:/main";
        }
        //返回登陆页面 给出提示
        model.addAttribute("msg","登录失败，用户名或密码错误");
        //转发登陆
        return "login";
    }
    @ResponseBody
    @GetMapping("/sql")
    public String sql(){
        jdbcTemplate.query(" select * from user",new BeanPropertyRowMapper<>(User.class));
        return "ok";
    }

    @GetMapping("/basic_table.html")
    public String basic_table(Model model){
        List<User> users = userMapper.selectList(null);
        model.addAttribute("users",users);
        return "table/basic_table";
    }
    @GetMapping("/edit.html")
    public String edit(String id,Model model){
        Object user =  userMapper.selectById(id);
        model.addAttribute("user",user);
        return "table/edit";
    }
    @PostMapping("/edit")
    public String editdo(User user){
        int i = userMapper.updateById(user);
        return "redirect:/basic_table.html";
    }
    @GetMapping("/del.html")
    public String del(String id){
        int i = userMapper.deleteById(id);
        return "redirect:/basic_table.html";
    }
    @GetMapping("add.html")
    public String addUI(){
        return "table/add";
    }
    @PostMapping("add")
    public String add(User user){
        userMapper.insert(user);
        return "redirect:/basic_table.html";
    }


}
